package com.ruoyi.merchant.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.merchant.domain.MerchantDishAudit;
import com.ruoyi.merchant.mapper.MerchantDishAuditMapper;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品审核Controller
 */
@RestController
@RequestMapping("/merchant/audit")
public class MerchantDishAuditController extends BaseController {

    @Autowired
    private MerchantDishAuditMapper dishAuditMapper;

    /**
     * 查询审核记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MerchantDishAudit dishAudit) {
        startPage();
        // 只查询当前商家的审核记录
        dishAudit.setMerchantId(MerchantSecurityUtils.getMerchantId());
        List<MerchantDishAudit> list = dishAuditMapper.selectDishAuditList(dishAudit);
        return getDataTable(list);
    }

    /**
     * 查询待审核记录列表
     */
    @GetMapping("/pending")
    public TableDataInfo pendingList() {
        startPage();
        MerchantDishAudit dishAudit = new MerchantDishAudit();
        dishAudit.setMerchantId(MerchantSecurityUtils.getMerchantId());
        dishAudit.setAuditStatus("0"); // 待审核
        List<MerchantDishAudit> list = dishAuditMapper.selectDishAuditList(dishAudit);
        return getDataTable(list);
    }

    /**
     * 获取审核记录详细信息
     */
    @GetMapping("/{auditId}")
    public AjaxResult getInfo(@PathVariable("auditId") Long auditId) {
        return success(dishAuditMapper.selectDishAuditByAuditId(auditId));
    }

    /**
     * 查询被拒绝的商品列表
     */
    @GetMapping("/rejected")
    public TableDataInfo rejectedList() {
        startPage();
        MerchantDishAudit dishAudit = new MerchantDishAudit();
        dishAudit.setMerchantId(MerchantSecurityUtils.getMerchantId());
        dishAudit.setAuditStatus("2"); // 审核拒绝
        List<MerchantDishAudit> list = dishAuditMapper.selectDishAuditList(dishAudit);
        return getDataTable(list);
    }

    /**
     * 根据商品ID查询最新审核记录（包含拒绝原因）
     */
    @GetMapping("/latest/{dishId}")
    public AjaxResult getLatestAudit(@PathVariable("dishId") Long dishId) {
        MerchantDishAudit audit = dishAuditMapper.selectLatestAuditByDishId(dishId);

        // 验证权限：只能查询自己的商品
        if (audit != null) {
            Long merchantId = MerchantSecurityUtils.getMerchantId();
            if (!merchantId.equals(audit.getMerchantId())) {
                return error("无权查看该审核记录");
            }
        }

        return success(audit);
    }
}
